<template>
  <view class="index-container">
    <!-- 微信登录弹窗 -->
    <view v-if="showLoginModal" class="login-modal-overlay" @click="closeLoginModal">
      <view :class="['login-modal', { 'modal-closing': isClosingModal }]" @click.stop>
        <!-- 关闭按钮 -->
        <view class="modal-close" @click="closeLoginModal">
          <u-icon name="close" size="40" color="#999" />
        </view>
        
        <!-- 微信图标 -->
        <view class="wechat-icon">
          <view class="wechat-logo-placeholder">
            <u-icon name="weixin-fill" size="120" color="#07C160" />
          </view>
        </view>
        
        <!-- 登录标题 -->
        <view class="login-title">
          <text class="title-main">微信登录</text>
          <text class="title-sub">使用微信账号快速登录</text>
        </view>
        
        <!-- 用户信息预览 -->
        <view class="user-preview">
          <image src="/static/default.png" class="preview-avatar" mode="aspectFill" />
          <text class="preview-name">微信用户</text>
        </view>
        
        <!-- 权限说明 -->
        <view class="permission-info">
          <view class="permission-item">
            <u-icon name="checkmark-circle" size="32" color="#07C160" />
            <text class="permission-text">获取您的公开信息（昵称、头像等）</text>
          </view>
          <view class="permission-item">
            <u-icon name="checkmark-circle" size="32" color="#07C160" />
            <text class="permission-text">获取您的手机号（用于订单通知）</text>
          </view>
        </view>
        
        <!-- 登录按钮 -->
        <button class="wechat-login-btn" @click="handleWechatLogin">
          <u-icon name="weixin-fill" size="40" color="#fff" />
          <text class="login-btn-text">微信登录</text>
        </button>
        
        <!-- 协议说明 -->
        <view class="agreement-text">
          <text class="agreement-desc">登录即表示同意</text>
          <text class="agreement-link" @click="showUserAgreement">《用户协议》</text>
          <text class="agreement-desc">和</text>
          <text class="agreement-link" @click="showPrivacyPolicy">《隐私政策》</text>
        </view>
      </view>
    </view>

    <!-- 顶部用户欢迎区 -->
    <view class="header-section">
      <view class="welcome-card">
        <view class="user-info">
          <image :src="userAvatar" class="avatar" mode="aspectFill" />
          <view class="user-text">
            <text class="welcome-text">{{ welcomeText }}</text>
            <text class="store-info">{{ storeInfo }}</text>
          </view>
        </view>
        <view class="weather-info" @longpress="resetLoginStatus">
          <u-icon name="wifi" size="40" color="#FFD700" />
          <text class="weather-text">今日适合用餐</text>
        </view>
      </view>
    </view>

    <!-- 轮播图区域 -->
    <view class="banner-section">
      <swiper class="banner-swiper" indicator-dots="true" autoplay="true" interval="3000" circular="true">
        <swiper-item v-for="(banner, index) in bannerList" :key="index">
          <image :src="banner.imageUrl" class="banner-image" mode="aspectFill" @click="onBannerClick(banner)" />
        </swiper-item>
      </swiper>
    </view>

    <!-- 秒杀活动横幅 -->
    <view class="seckill-banner" @click="goToSeckillList">
      <view class="seckill-content">
        <view class="seckill-left">
          <view class="seckill-icon">
            <u-icon name="bag" size="50" color="#fff" />
          </view>
          <view class="seckill-info">
            <text class="seckill-title">限时秒杀</text>
            <text class="seckill-subtitle">超值优惠 · 抢先体验</text>
          </view>
        </view>
        <view class="seckill-time">
          <text class="time-label">距离结束</text>
          <view class="countdown-display">
            <text class="time-num">{{ seckillCountdown.hour }}</text>
            <text class="time-split">:</text>
            <text class="time-num">{{ seckillCountdown.minute }}</text>
            <text class="time-split">:</text>
            <text class="time-num">{{ seckillCountdown.second }}</text>
          </view>
        </view>
      </view>
      <u-icon name="arrow-right" size="30" color="#FFB800" />
    </view>

    <!-- 功能菜单网格 -->
    <view class="function-grid">
      <view class="grid-title">
        <text class="title-text">服务功能</text>
        <text class="title-desc">一站式餐饮体验</text>
      </view>
      <view class="grid-container">
        <view class="grid-item" @click="goOrderFood">
          <view class="item-icon scan-icon">
            <u-icon name="scan" size="60" color="#007AFF" />
          </view>
          <text class="item-label">扫码点餐</text>
          <text class="item-desc">快速便捷</text>
        </view>
        
        <view class="grid-item" @click="goMenuList">
          <view class="item-icon menu-icon">
            <u-icon name="list" size="60" color="#1AAD19" />
          </view>
          <text class="item-label">菜单浏览</text>
          <text class="item-desc">精选美食</text>
        </view>
        
        <view class="grid-item" @click="goToSeckillList">
          <view class="item-icon seckill-icon">
            <u-icon name="bag" size="60" color="#FF5000" />
          </view>
          <text class="item-label">限时秒杀</text>
          <text class="item-desc">超值优惠</text>
        </view>
        
        <view class="grid-item" @click="goUserCenter">
          <view class="item-icon user-icon">
            <u-icon name="account" size="60" color="#8B5CF6" />
          </view>
          <text class="item-label">个人中心</text>
          <text class="item-desc">会员服务</text>
        </view>
        
        <view class="grid-item" @click="goAIService">
          <view class="item-icon ai-icon">
            <u-icon name="chat" size="60" color="#F59E0B" />
          </view>
          <text class="item-label">AI助手</text>
          <text class="item-desc">智能推荐</text>
        </view>
        
        <view class="grid-item" @click="goVIP">
          <view class="item-icon vip-icon">
            <u-icon name="star" size="60" color="#EC4899" />
          </view>
          <text class="item-label">会员特权</text>
          <text class="item-desc">专享优惠</text>
        </view>
      </view>
    </view>


  </view>
</template>

<script setup>
import { ref, onMounted, onUnmounted, reactive } from 'vue'
import { login } from "@/api/login"

// 登录弹窗控制
const showLoginModal = ref(false)
const isClosingModal = ref(false)
const isLoggedIn = ref(false)

// 用户信息
const userAvatar = ref('/static/default-avatar.png')
const welcomeText = ref('欢迎光临')
const storeInfo = ref('')

// 移除模拟用户信息，使用真实的微信登录数据

// 轮播图数据
const bannerList = ref([
  { imageUrl: '/static/banner1.jpg', linkUrl: '' },
  { imageUrl: '/static/banner2.jpg', linkUrl: '' },
  { imageUrl: '/static/banner3.jpg', linkUrl: '' }
])

// 秒杀倒计时
const seckillCountdown = reactive({
  hour: '02',
  minute: '30',
  second: '45'
})



onMounted(() => {
  // 检查登录状态
  checkLoginStatus()
  
  initUserInfo()
  startCountdown()
  updateStoreInfo()
  
  // 监听门店信息更新事件
  uni.$on('storeInfoUpdated', () => {
    updateStoreInfo()
  })
})

onUnmounted(() => {
  // 移除事件监听
  uni.$off('storeInfoUpdated')
})

// 检查登录状态
function checkLoginStatus() {
  const userId = uni.getStorageSync('userId')
  
  if (userId) {
    isLoggedIn.value = true
    // 如果已登录，从缓存中恢复用户信息
    const cachedUserInfo = uni.getStorageSync('userInfo')
    if (cachedUserInfo) {
      userAvatar.value = cachedUserInfo.avatar
      welcomeText.value = `你好，${cachedUserInfo.nickname}`
    }
  }
  // 移除模拟登录弹窗逻辑，只使用真实的微信登录
}

// 关闭登录弹窗
function closeLoginModal() {
  // 开始关闭动画
  isClosingModal.value = true
  
  // 延迟关闭弹窗
  setTimeout(() => {
    showLoginModal.value = false
    isClosingModal.value = false
  }, 300)
}

// 处理微信登录（现在不需要了，因为在initUserInfo中已经处理了真实登录）
function handleWechatLogin() {
  // 关闭弹窗即可，真实登录已经在initUserInfo中完成
  closeLoginModal()
}

// 显示用户协议
function showUserAgreement() {
  uni.showModal({
    title: '用户协议',
    content: '这里是用户协议的内容...',
    showCancel: false,
    confirmText: '我知道了'
  })
}

// 显示隐私政策
function showPrivacyPolicy() {
  uni.showModal({
    title: '隐私政策',
    content: '这里是隐私政策的内容...',
    showCancel: false,
    confirmText: '我知道了'
  })
}

// 重置登录状态（长按天气图标触发，用于测试）
function resetLoginStatus() {
  uni.showModal({
    title: '重置登录状态',
    content: '确定要重置登录状态吗？将清除所有登录信息。',
    success: (res) => {
      if (res.confirm) {
        // 清除登录相关的缓存
        uni.removeStorageSync('userId')
        uni.removeStorageSync('openId')
        uni.removeStorageSync('userInfo')
        
        // 重置页面状态
        isLoggedIn.value = false
        isClosingModal.value = false
        userAvatar.value = '/static/default-avatar.png'
        welcomeText.value = '欢迎光临'
        
        uni.showToast({
          title: '已重置登录状态',
          icon: 'success'
        })
        
        // 重新调用登录初始化
        setTimeout(() => {
          initUserInfo()
        }, 1000)
      }
    }
  })
}

// 更新门店信息显示
function updateStoreInfo() {
  const cachedStoreId = uni.getStorageSync('storeId')
  const cachedTableNo = uni.getStorageSync('tableNo')
  
  if (cachedStoreId && cachedTableNo) {
    storeInfo.value = `门店${cachedStoreId} · ${cachedTableNo}号桌`
  } else {
    storeInfo.value = '请先扫码'
  }
}

// 初始化用户信息
function initUserInfo() {
  uni.login({
    provider: 'weixin',
    success: function (loginRes) {
      console.log('微信登录code:', loginRes.code)
      login(loginRes.code).then(res => {
        console.log('登录响应:', res)
        console.log('登录响应中的userId类型:', typeof res.userId, '值:', res.userId)
        
        // 保存openId和userId
        uni.setStorageSync("openId", res.openId)
        uni.setStorageSync("userId", res.userId)
        console.log('保存的userId:', res.userId)
        console.log('保存后立即读取的userId:', uni.getStorageSync('userId'))
        console.log('保存后立即读取的userId类型:', typeof uni.getStorageSync('userId'))
        
        // 清理旧的购物车数据（因为用户ID可能发生变化）
        uni.removeStorageSync('cartList')
        console.log('已清理旧的购物车数据')
        
        // 标记已登录
        isLoggedIn.value = true
        
        // 获取用户信息
        uni.getUserInfo({
          provider: 'weixin',
          success: function(info) {
            const wxUserInfo = info.userInfo
            const userInfo = {
              nickname: wxUserInfo.nickName || '微信用户',
              avatar: wxUserInfo.avatarUrl || '/static/default.png'
            }
            
            // 保存用户信息
            uni.setStorageSync('userInfo', userInfo)
            
            // 更新页面显示
            userAvatar.value = userInfo.avatar
            welcomeText.value = `你好，${userInfo.nickname}`
            
            console.log('用户信息:', wxUserInfo)
            console.log('保存的用户信息:', userInfo)
          },
          fail: function(error) {
            console.log('获取用户信息失败:', error)
            // 使用默认用户信息
            const defaultUserInfo = {
              nickname: '微信用户',
              avatar: '/static/default.png'
            }
            uni.setStorageSync('userInfo', defaultUserInfo)
            userAvatar.value = defaultUserInfo.avatar
            welcomeText.value = `你好，${defaultUserInfo.nickname}`
          }
        })
      }).catch(error => {
        console.error('登录失败:', error)
      })
    },
    fail: function(error) {
      console.error('微信登录失败:', error)
    }
  })
}

// 启动倒计时
function startCountdown() {
  setInterval(() => {
    let second = parseInt(seckillCountdown.second)
    let minute = parseInt(seckillCountdown.minute)
    let hour = parseInt(seckillCountdown.hour)
    
    if (second > 0) {
      second--
    } else if (minute > 0) {
      second = 59
      minute--
    } else if (hour > 0) {
      second = 59
      minute = 59
      hour--
    }
    
    seckillCountdown.second = String(second).padStart(2, '0')
    seckillCountdown.minute = String(minute).padStart(2, '0')
    seckillCountdown.hour = String(hour).padStart(2, '0')
  }, 1000)
}

// 检查扫码状态
function checkScanStatus() {
  const cachedStoreId = uni.getStorageSync('storeId')
  const cachedTableNo = uni.getStorageSync('tableNo')
  
  if (!cachedStoreId || !cachedTableNo) {
    uni.showModal({
      title: '温馨提示',
      content: '请先扫描桌上的二维码再开始使用',
      showCancel: false,
      confirmText: '去扫码',
      success: () => {
        uni.switchTab({
          url: '/pages/scanCode/scanCode'
        })
      }
    })
    return false
  }
  return true
}

// 页面跳转函数
function goToSeckillList() {
  if (checkScanStatus()) {
    uni.navigateTo({ url: '/pages/seckill/list' })
  }
}

function goOrderFood() {
  if (checkScanStatus()) {
    uni.switchTab({ url: '/pages/orderFood/orderFood' })
  }
}

function goUserCenter() {
  uni.switchTab({ url: '/pages/userCenter/userCenter' })
}

function goMenuList() {
  if (checkScanStatus()) {
    uni.switchTab({ url: '/pages/orderFood/orderFood' })
  }
}

function goAIService() {
  if (checkScanStatus()) {
    uni.navigateTo({ url: '/pages/AIService/AIService' })
  }
}

function goVIP() {
  uni.navigateTo({ url: '/pages/VIP/VIP' })
}

function onBannerClick(banner) {
  if (banner.linkUrl) {
    uni.navigateTo({ url: banner.linkUrl })
  }
}


</script>

<style scoped>
.index-container {
  min-height: 100vh;
  background: linear-gradient(180deg, #f8faff 0%, #ffffff 100%);
}

/* 登录弹窗样式 */
.login-modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: flex-end;
  z-index: 9999;
  animation: fadeIn 0.3s ease-out;
}

.login-modal {
  width: 100%;
  background: #ffffff;
  border-radius: 40rpx 40rpx 0 0;
  padding: 60rpx 40rpx 80rpx;
  position: relative;
  animation: slideUp 0.4s cubic-bezier(0.25, 0.46, 0.45, 0.94);
}

.login-modal.modal-closing {
  animation: slideDown 0.3s ease-in-out;
}

.modal-close {
  position: absolute;
  top: 30rpx;
  right: 30rpx;
  width: 60rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  background: #f5f5f5;
}

.wechat-icon {
  display: flex;
  justify-content: center;
  margin-bottom: 40rpx;
}

.wechat-logo-placeholder {
  width: 120rpx;
  height: 120rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.login-title {
  text-align: center;
  margin-bottom: 50rpx;
}

.title-main {
  display: block;
  font-size: 48rpx;
  font-weight: bold;
  color: #1a1a1a;
  margin-bottom: 16rpx;
}

.title-sub {
  display: block;
  font-size: 28rpx;
  color: #666666;
}

.user-preview {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 50rpx;
  padding: 40rpx;
  background: #f8f9fa;
  border-radius: 20rpx;
}

.preview-avatar {
  width: 120rpx;
  height: 120rpx;
  border-radius: 50%;
  margin-bottom: 20rpx;
  border: 4rpx solid #07C160;
}

.preview-name {
  font-size: 32rpx;
  font-weight: 600;
  color: #1a1a1a;
}

.permission-info {
  margin-bottom: 60rpx;
}

.permission-item {
  display: flex;
  align-items: center;
  margin-bottom: 24rpx;
}

.permission-text {
  font-size: 28rpx;
  color: #666666;
  margin-left: 16rpx;
  flex: 1;
}

.wechat-login-btn {
  width: 100%;
  height: 100rpx;
  background: linear-gradient(135deg, #07C160 0%, #00A854 100%);
  border: none;
  border-radius: 50rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 40rpx;
  box-shadow: 0 8rpx 24rpx rgba(7, 193, 96, 0.3);
}

.login-btn-text {
  color: #ffffff;
  font-size: 36rpx;
  font-weight: bold;
  margin-left: 16rpx;
}

.agreement-text {
  text-align: center;
  line-height: 1.6;
}

.agreement-desc {
  font-size: 24rpx;
  color: #999999;
}

.agreement-link {
  font-size: 24rpx;
  color: #07C160;
  text-decoration: underline;
}

/* 动画效果 */
@keyframes fadeIn {
  from { opacity: 0; }
  to { opacity: 1; }
}

@keyframes slideUp {
  from { 
    transform: translateY(100%);
    opacity: 0;
  }
  to { 
    transform: translateY(0);
    opacity: 1;
  }
}

@keyframes slideDown {
  from { 
    transform: translateY(0);
    opacity: 1;
  }
  to { 
    transform: translateY(100%);
    opacity: 0;
  }
}

/* 顶部欢迎区 */
.header-section {
  padding: 40rpx 30rpx 20rpx;
}

.welcome-card {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 30rpx;
  border-radius: 20rpx;
  box-shadow: 0 8rpx 24rpx rgba(102, 126, 234, 0.3);
}

.user-info {
  display: flex;
  align-items: center;
}

.avatar {
  width: 80rpx;
  height: 80rpx;
  border-radius: 50%;
  margin-right: 20rpx;
  border: 3rpx solid rgba(255, 255, 255, 0.3);
}

.user-text {
  display: flex;
  flex-direction: column;
}

.welcome-text {
  color: #ffffff;
  font-size: 32rpx;
  font-weight: 600;
  margin-bottom: 4rpx;
}

.store-info {
  color: rgba(255, 255, 255, 0.8);
  font-size: 22rpx;
}

.weather-info {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.weather-text {
  color: rgba(255, 255, 255, 0.9);
  font-size: 24rpx;
  margin-top: 8rpx;
}

/* 轮播图 */
.banner-section {
  padding: 0 30rpx 30rpx;
}

.banner-swiper {
  height: 320rpx;
  border-radius: 16rpx;
  overflow: hidden;
}

.banner-image {
  width: 100%;
  height: 100%;
}

/* 秒杀横幅 */
.seckill-banner {
  margin: 0 30rpx 30rpx;
  background: linear-gradient(135deg, #FF6B6B 0%, #FF8E53 100%);
  padding: 30rpx;
  border-radius: 16rpx;
  display: flex;
  align-items: center;
  justify-content: space-between;
  box-shadow: 0 8rpx 24rpx rgba(255, 107, 107, 0.3);
}

.seckill-content {
  display: flex;
  align-items: center;
  flex: 1;
}

.seckill-left {
  display: flex;
  align-items: center;
}

.seckill-icon {
  margin-right: 20rpx;
}

.seckill-title {
  color: #ffffff;
  font-size: 36rpx;
  font-weight: bold;
}

.seckill-subtitle {
  color: rgba(255, 255, 255, 0.9);
  font-size: 24rpx;
  margin-top: 8rpx;
}

.seckill-time {
  text-align: right;
}

.time-label {
  color: rgba(255, 255, 255, 0.8);
  font-size: 22rpx;
}

.countdown-display {
  display: flex;
  align-items: center;
  margin-top: 8rpx;
}

.time-num {
  background: rgba(255, 255, 255, 0.2);
  color: #ffffff;
  padding: 6rpx 12rpx;
  border-radius: 8rpx;
  font-size: 28rpx;
  font-weight: bold;
  min-width: 44rpx;
  text-align: center;
}

.time-split {
  color: #ffffff;
  margin: 0 8rpx;
  font-weight: bold;
}

/* 功能网格 */
.function-grid {
  padding: 0 30rpx 40rpx;
}

.grid-title {
  margin-bottom: 30rpx;
}

.title-text {
  font-size: 36rpx;
  font-weight: bold;
  color: #1a1a1a;
}

.title-desc {
  color: #666666;
  font-size: 26rpx;
  margin-left: 20rpx;
}

.grid-container {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 30rpx;
}

.grid-item {
  background: #ffffff;
  padding: 40rpx 20rpx;
  border-radius: 20rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
}

.grid-item:active {
  transform: scale(0.95);
}

.item-icon {
  width: 100rpx;
  height: 100rpx;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 20rpx;
}

.scan-icon { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); }
.menu-icon { background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%); }
.seckill-icon { background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%); }
.user-icon { background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%); }
.ai-icon { background: linear-gradient(135deg, #fa709a 0%, #fee140 100%); }
.vip-icon { background: linear-gradient(135deg, #a8edea 0%, #fed6e3 100%); }

.item-label {
  font-size: 28rpx;
  color: #1a1a1a;
  font-weight: 600;
  margin-bottom: 8rpx;
}

.item-desc {
  font-size: 22rpx;
  color: #666666;
}


</style>
